package com.lorenzogao.lib_view

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import com.lorenzogao.lib_view.ext.px2dp
import kotlin.math.sqrt

/**
 *  create by LorenzoGao
 *  email: 2508719070@qq.com
 *  TIME: 2019-11-13 13:25
 *  description:
 */


class CityLoadView : View {


    enum class Status {
        TRIANGLE, ROUND, SQUARE
    }

    private val defalutWidthAndHegiht = 100

    private var mStatus = Status.TRIANGLE

    private val mPaint by lazy {
        Paint().apply {
            style = Paint.Style.FILL
            isAntiAlias = true
        }
    }





    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        var width = MeasureSpec.getSize(widthMeasureSpec)
        var height = MeasureSpec.getSize(heightMeasureSpec)

        if (widthMode == MeasureSpec.AT_MOST) {
            width = defalutWidthAndHegiht.px2dp(context)
        }
        if (heightMode == MeasureSpec.AT_MOST) {
            height = defalutWidthAndHegiht.px2dp(context)
        }

        setMeasuredDimension(if (width > height) height else width, if (width > height) height else width)

    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        mStatus = when (mStatus) {
            Status.TRIANGLE -> {
                drawTriangle(canvas)
                Status.ROUND
            }
            Status.ROUND -> {
                mPaint.color=Color.RED
                canvas?.drawCircle((width / 2).toFloat(), (height / 2).toFloat(), (width / 2).toFloat(), mPaint)
                Status.SQUARE
            }
            else -> {
                mPaint.color=Color.GREEN
                val rectF = RectF(0f, 0f, width.toFloat(), height.toFloat())
                canvas.drawRect(rectF, mPaint)
                Status.TRIANGLE
            }
        }

    }


    private fun drawTriangle(canvas: Canvas) {
        mPaint.color=Color.YELLOW
        val path = Path()
        path.moveTo((width / 2).toFloat(), 0f)
        path.lineTo(width.toFloat(), ((height/2)* sqrt(3.0)).toFloat())
        path.lineTo(0f, ((height/2)* sqrt(3.0)).toFloat())
        path.close()
        canvas.drawPath(path, mPaint)
    }

    fun exchange() {
        invalidate()
    }

}